package com.jeecg.demo.service.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.jeecgframework.core.constant.Globals;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jeecg.demo.entity.FreezeDepositEntity;
import com.jeecg.demo.service.ThawMarginServiceI;

@Service("thawMarginService")
@Transactional
public class ThawMarginServiceImpl extends CommonServiceImpl implements
        ThawMarginServiceI {

    private static final Logger logger = LoggerFactory.getLogger(ThawMarginServiceImpl.class);

    @Transactional
    public void doThaw() throws Exception {

        String sql = "SELECT f.*,p.POSTATUS FROM FREEZE_DEPOSIT f,POSTORDER p WHERE f.SUBECTID=315 and f.TYPE=0 and f.STATUS=1 and p.POCODE=f.POCODE and p.POSTATUS in (8,5,0,-1)";
        List<Map<String, Object>> list = findForJdbc(sql);
        if (list.size() > 0) {


            for (Map<String, Object> map : list) {
                String postatus = String.valueOf(map.get("POSTATUS"));
                String id = String.valueOf(map.get("ID"));
                String traderCode = String.valueOf(map.get("TRADERCODE"));
                String tranferMoeny = String.valueOf(map.get("TRANFERMOENY"));
                String sertalNo = String.valueOf(map.get("SERTALNO"));
                String pocode = String.valueOf(map.get("POCODE"));

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date();
                String time = sdf.format(date);
                Integer subectId = 315;
                Integer type = 1;
                String demo = "解冻保证金";

                logger.info("pocode =" + pocode + ", tradercode = " + traderCode + ", sertalno = " + sertalNo);

                boolean result = goSettlement(traderCode, subectId, tranferMoeny, time, sertalNo, type, demo);
                if (result) {
                    FreezeDepositEntity depositEntity = getEntity(FreezeDepositEntity.class, Integer.valueOf(id));
                    depositEntity.setStatus(0);
                    saveOrUpdate(depositEntity);

                    FreezeDepositEntity free = new FreezeDepositEntity();
                    free.setTraderCode(traderCode);
                    free.setPocode(pocode);
                    free.setSertalNo(sertalNo);
                    free.setTranferMoeny(tranferMoeny);
                    free.setTransferTime(time);
                    free.setStatus(1);
                    free.setType(type);
                    free.setSubectId(subectId);
                    free.setDemo(demo);
                    save(free);

                    if ("5".equals(postatus)) {
                        String succSql = "SELECT t.TRADECODE FROM V_ECP_ACCEPTORDER v,TRADER t WHERE v.pocode = ? and v.AOSTATUS = 2 and t.TRADERID=v.AOTRADERID and t.TRADECODE=?";
                        List<Map<String, Object>> succList = findForJdbc(succSql, pocode, traderCode);
                        if (succList.size() > 0) {
                            Integer sub = 316;
                            Integer tp = 0;
                            String dm = "履约保证金冻结";
                            boolean succResult = goSettlement(traderCode, sub, tranferMoeny, time, sertalNo, tp, dm);
                            if (succResult) {
                                FreezeDepositEntity freezeDepositEntity = new FreezeDepositEntity();
                                freezeDepositEntity.setPocode(pocode);
                                freezeDepositEntity.setSertalNo(sertalNo);
                                freezeDepositEntity.setTranferMoeny(tranferMoeny);
                                freezeDepositEntity.setTransferTime(time);
                                freezeDepositEntity.setStatus(1);

                                freezeDepositEntity.setTraderCode(traderCode);
                                freezeDepositEntity.setType(tp);
                                freezeDepositEntity.setSubectId(sub);
                                freezeDepositEntity.setDemo(dm);
                                save(freezeDepositEntity);
                            }
                        }
                    }
                }
            }
        }
    }

    private boolean goSettlement(String traderCode, Integer subectId, String tranferMoeny, String time, String sertalNo, Integer type, String demo) throws Exception {
        Map<String, Object> mapData = new HashMap();
        mapData.put("firmId", traderCode);
        mapData.put("subectId", subectId);
        mapData.put("tranferMoeny", tranferMoeny);
        mapData.put("transferTime", time);
        mapData.put("sertalNo", sertalNo);
        mapData.put("type", type);
        mapData.put("demo", demo);

        String params = JSON.toJSONString(mapData);
        String methond = "freezeDeposit";
        return doSettlement(params, methond);
    }

    public boolean doSettlement(String params, String methond) throws Exception {
        if (StringUtils.isNotEmpty(methond)) {
            String url = Globals.SETTLEMENT_URL + methond;
            String doPost = doPost(url, "msg=" + params);
            if (StringUtils.isNotEmpty(doPost)) {
                JSONObject parse = (JSONObject) JSON.parse(doPost);
                logger.info(parse.toString());
                String flag = parse.get("responsecode").toString();
                if (flag.length() > 5) {
                    return true;
                }
            }
        }
        return false;
    }

    public static String doPost(String httpUrl, String param) {

        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        String result = null;
        try {
            URL url = new URL(httpUrl);
            // 通过远程url连接对象打开连接
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接请求方式
            connection.setRequestMethod("POST");
            // 设置连接主机服务器超时时间：15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取主机服务器返回数据超时时间：60000毫秒
            connection.setReadTimeout(60000);

            // 默认值为：false，当向远程服务器传送数据/写数据时，需要设置为true
            connection.setDoOutput(true);
            // 默认值为：true，当前向远程服务读取数据时，设置为true，该参数可有可无
            connection.setDoInput(true);
            // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
            connection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            // 设置鉴权信息：Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
            connection.setRequestProperty("Authorization",
                    "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
            // 通过连接对象获取一个输出流
            os = connection.getOutputStream();
            // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
            os.write(param.getBytes());
            // 通过连接对象获取一个输入流，向远程读取
            if (connection.getResponseCode() == 200) {

                is = connection.getInputStream();
                // 对输入流对象进行包装:charset根据工作项目组的要求来设置
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

                StringBuffer sbf = new StringBuffer();
                String temp = null;
                // 循环遍历一行一行读取数据
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        }
        catch (MalformedURLException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != os) {
                try {
                    os.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 断开与远程地址url的连接
            connection.disconnect();
        }
        return result;
    }

}
